<template>
  <view class="order-confirm">
    <!-- 导航栏 -->
    <NavBar title="确认订单" />

    <!-- 收货地址 -->
    <view class="address-section" @click="selectAddress">
      <view v-if="selectedAddress" class="address-info">
        <view class="address-header">
          <text class="name">{{ selectedAddress.name }}</text>
          <text class="phone">{{ selectedAddress.phone }}</text>
        </view>
        <view class="address-detail">
          {{ getFullAddress(selectedAddress) }}
        </view>
      </view>
      <view v-else class="address-empty">
        <text>请选择收货地址</text>
      </view>
      <Location size="20" class="address-icon" />
      <Right size="16" class="right-icon" />
    </view>

    <!-- 商品信息 -->
    <view class="goods-section">
      <view class="section-title">商品信息</view>
      <view class="goods-list">
        <view class="goods-item" v-for="(item, index) in orderGoods" :key="index">
          <image :src="item.goods.cover" class="goods-image" />
          <view class="goods-info">
            <text class="goods-name">{{ item.goods.title }}</text>
            <text class="goods-sku" v-if="item.skuText">{{ item.skuText }}</text>
            <view class="goods-price-qty">
              <nut-price :price="item.goods.price" size="normal" />
              <text class="goods-qty">x{{ item.quantity }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 配送方式 -->
    <view class="delivery-section">
      <nut-cell title="配送方式" :desc="deliveryMethod.name" is-link @click="showDeliveryPicker = true" />
    </view>

    <!-- 优惠券 -->
    <view class="coupon-section">
      <nut-cell title="优惠券" :desc="selectedCoupon ? selectedCoupon.name : '暂无可用优惠券'" is-link @click="showCouponList = true" />
    </view>

    <!-- 订单备注 -->
    <view class="remark-section">
      <nut-cell title="订单备注">
        <template #desc>
          <nut-input
            v-model="remark"
            placeholder="选填，请先和商家协商一致"
            type="text"
            :border="false"
            max-length="50"
          />
        </template>
      </nut-cell>
    </view>

    <!-- 金额明细 -->
    <view class="amount-section">
      <view class="amount-item">
        <text>商品金额</text>
        <nut-price :price="goodsAmount" size="normal" />
      </view>
      <view class="amount-item">
        <text>运费</text>
        <nut-price :price="deliveryFee" size="normal" />
      </view>
      <view class="amount-item" v-if="discountAmount > 0">
        <text>优惠</text>
        <text class="discount">-<nut-price :price="discountAmount" size="normal" /></text>
      </view>
      <view class="amount-total">
        <text>实付款</text>
        <nut-price :price="totalAmount" size="large" class="total-price" />
      </view>
    </view>

    <!-- 底部提交栏 -->
    <view class="submit-bar">
      <view class="price-info">
        <text>合计：</text>
        <nut-price :price="totalAmount" size="normal" class="total-price" />
      </view>
      <nut-button type="primary" @click="submitOrder" :disabled="!canSubmit">提交订单</nut-button>
    </view>

    <!-- 配送方式选择弹窗 -->
    <nut-popup position="bottom" v-model:visible="showDeliveryPicker">
      <view class="picker-container">
        <view class="picker-header">
          <text>选择配送方式</text>
          <Close class="close-icon" @click="showDeliveryPicker = false" />
        </view>
        <view class="picker-content">
          <nut-cell-group>
            <nut-cell 
              v-for="(item, index) in deliveryMethods" 
              :key="index"
              :title="item.name"
              @click="selectDeliveryMethod(item)"
            >
              <template #desc>
                <nut-price v-if="item.fee > 0" :price="item.fee" size="small" />
                <text v-else class="free-delivery">免运费</text>
              </template>
              <template #link>
                <nut-checkbox v-model="item.checked" shape="button" />
              </template>
            </nut-cell>
          </nut-cell-group>
        </view>
      </view>
    </nut-popup>

    <!-- 优惠券选择弹窗 -->
    <nut-popup position="bottom" v-model:visible="showCouponList">
      <view class="picker-container">
        <view class="picker-header">
          <text>选择优惠券</text>
          <Close class="close-icon" @click="showCouponList = false" />
        </view>
        <view class="picker-content">
          <view v-if="coupons.length === 0" class="empty-coupons">
            <text>暂无可用优惠券</text>
          </view>
          <nut-cell-group v-else>
            <nut-cell 
              v-for="(item, index) in coupons" 
              :key="index"
              :title="item.name"
              @click="selectCoupon(item)"
            >
              <template #desc>
                <text>{{ item.description }}</text>
              </template>
              <template #link>
                <nut-checkbox v-model="item.checked" shape="button" />
              </template>
            </nut-cell>
          </nut-cell-group>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { Location, Right, Close } from '@nutui/icons-vue-taro'
import NavBar from '../../components/NavBar/index.vue'
import orderApi from '../../api/order'
import goodsApi from '../../api/goods'
import userApi from '../../api/user'

// 获取路由参数
const router = Taro.getCurrentInstance().router
const goodsId = router?.params?.goodsId
const quantity = Number(router?.params?.quantity || 1)
const skuText = router?.params?.skuText ? decodeURIComponent(router?.params?.skuText) : ''
const cartIds = router?.params?.cartIds

// 订单商品
const orderGoods = ref([])

// 收货地址
const selectedAddress = ref(null)

// 配送方式
const showDeliveryPicker = ref(false)
const deliveryMethods = ref([
  { id: 1, name: '普通快递', fee: 0, checked: true },
  { id: 2, name: '顺丰速运', fee: 12, checked: false },
  { id: 3, name: '同城配送', fee: 8, checked: false }
])
const deliveryMethod = computed(() => {
  return deliveryMethods.value.find(item => item.checked) || deliveryMethods.value[0]
})

// 优惠券
const showCouponList = ref(false)
const coupons = ref([])
const selectedCoupon = computed(() => {
  return coupons.value.find(item => item.checked)
})

// 订单备注
const remark = ref('')

// 金额计算
const goodsAmount = computed(() => {
  return orderGoods.value.reduce((total, item) => {
    return total + Number(item.goods.price) * item.quantity
  }, 0).toFixed(2)
})

const deliveryFee = computed(() => {
  return deliveryMethod.value.fee.toFixed(2)
})

const discountAmount = computed(() => {
  return selectedCoupon.value ? selectedCoupon.value.amount.toFixed(2) : '0.00'
})

const totalAmount = computed(() => {
  const total = Number(goodsAmount.value) + Number(deliveryFee.value) - Number(discountAmount.value)
  return total > 0 ? total.toFixed(2) : '0.00'
})

// 是否可提交订单
const canSubmit = computed(() => {
  return selectedAddress.value && orderGoods.value.length > 0
})

// 获取完整地址
const getFullAddress = (address) => {
  if (!address) return ''
  return `${address.province}${address.city}${address.district}${address.detail}`
}

// 选择收货地址
const selectAddress = () => {
  Taro.navigateTo({
    url: '/pages/address/list?select=true',
    events: {
      // 监听选择地址事件
      selectAddress: (address) => {
        selectedAddress.value = address
      }
    }
  })
}

// 选择配送方式
const selectDeliveryMethod = (method) => {
  deliveryMethods.value.forEach(item => {
    item.checked = item.id === method.id
  })
  showDeliveryPicker.value = false
}

// 选择优惠券
const selectCoupon = (coupon) => {
  coupons.value.forEach(item => {
    item.checked = item.id === coupon.id
  })
  showCouponList.value = false
}

// 提交订单
const submitOrder = () => {
  if (!canSubmit.value) {
    Taro.showToast({
      title: '请先选择收货地址',
      icon: 'none'
    })
    return
  }

  const orderData = {
    goods: orderGoods.value.map(item => ({
      goodsId: item.goods.id,
      quantity: item.quantity
    })),
    address: {
      name: selectedAddress.value.name,
      phone: selectedAddress.value.phone,
      province: selectedAddress.value.province,
      city: selectedAddress.value.city,
      district: selectedAddress.value.district,
      detail: selectedAddress.value.detail
    },
    deliveryMethod: deliveryMethod.value.id,
    couponId: selectedCoupon.value ? selectedCoupon.value.id : undefined,
    remark: remark.value
  }

  orderApi.createOrder(orderData).then(res => {
    // 跳转到支付页面
    Taro.navigateTo({
      url: `/pages/order/payment?id=${res.data.id}&amount=${totalAmount.value}`
    })
  }).catch(err => {
    Taro.showToast({
      title: err.message || '创建订单失败',
      icon: 'none'
    })
  })
}

// 获取商品信息
const fetchGoodsInfo = () => {
  if (goodsId) {
    // 从商品详情页下单
    goodsApi.getGoodsDetail(goodsId).then(res => {
      orderGoods.value = [{
        goods: res.data,
        quantity: quantity,
        skuText: skuText
      }]
    }).catch(err => {
      Taro.showToast({
        title: err.message || '获取商品信息失败',
        icon: 'none'
      })
    })
  } else if (cartIds) {
    // 从购物车下单
    const ids = cartIds.split(',')
    // 这里应该调用获取购物车选中商品的接口
    // 由于没有具体接口，这里模拟数据
    orderGoods.value = [
      {
        goods: {
          id: 1,
          title: '示例商品1',
          price: '99.00',
          cover: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/223778/18/6959/103158/61cc7965E6f1e0dda/a4a0450759d5614e.jpg'
        },
        quantity: 1,
        skuText: '黑色，128GB'
      },
      {
        goods: {
          id: 2,
          title: '示例商品2',
          price: '199.00',
          cover: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/180776/36/4489/93104/60a0a38fEaae1d3f7/e57e4d9c553c6413.jpg'
        },
        quantity: 2,
        skuText: '白色，256GB'
      }
    ]
  }
}

// 获取默认地址
const fetchDefaultAddress = () => {
  userApi.getAddressList().then(res => {
    const defaultAddress = res.data.find(item => item.isDefault)
    if (defaultAddress) {
      selectedAddress.value = defaultAddress
    } else if (res.data.length > 0) {
      selectedAddress.value = res.data[0]
    }
  }).catch(err => {
    console.error('获取地址失败', err)
  })
}

// 获取可用优惠券
const fetchCoupons = () => {
  // 模拟数据，实际应该调用获取优惠券接口
  coupons.value = [
    { id: 1, name: '满100减10', description: '订单满100元可用', amount: 10, checked: false },
    { id: 2, name: '满200减30', description: '订单满200元可用', amount: 30, checked: false },
    { id: 3, name: '满300减50', description: '订单满300元可用', amount: 50, checked: false }
  ]
}

// 页面加载
onMounted(() => {
  fetchGoodsInfo()
  fetchDefaultAddress()
  fetchCoupons()
})
</script>

<style lang="scss">
.order-confirm {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 60px;
}

.address-section {
  position: relative;
  background-color: #fff;
  margin-bottom: 10px;
  padding: 16px;
  
  .address-info {
    padding-right: 20px;
    
    .address-header {
      margin-bottom: 8px;
      
      .name {
        font-size: 16px;
        font-weight: bold;
        margin-right: 10px;
      }
      
      .phone {
        color: #666;
      }
    }
    
    .address-detail {
      font-size: 14px;
      color: #333;
      line-height: 1.4;
    }
  }
  
  .address-empty {
    padding: 10px 0;
    color: #999;
  }
  
  .address-icon {
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    display: none; // 暂时隐藏，根据设计调整
  }
  
  .right-icon {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
  }
}

.goods-section {
  background-color: #fff;
  margin-bottom: 10px;
  padding: 16px;
  
  .section-title {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 10px;
  }
  
  .goods-list {
    .goods-item {
      display: flex;
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .goods-image {
        width: 80px;
        height: 80px;
        border-radius: 4px;
        flex-shrink: 0;
      }
      
      .goods-info {
        flex: 1;
        margin-left: 10px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        
        .goods-name {
          font-size: 14px;
          line-height: 1.4;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .goods-sku {
          font-size: 12px;
          color: #999;
          margin: 4px 0;
        }
        
        .goods-price-qty {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .goods-qty {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }
}

.delivery-section,
.coupon-section,
.remark-section {
  background-color: #fff;
  margin-bottom: 10px;
}

.amount-section {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 10px;
  
  .amount-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    font-size: 14px;
    color: #666;
    
    .discount {
      color: #ff5000;
    }
  }
  
  .amount-total {
    display: flex;
    justify-content: space-between;
    padding-top: 10px;
    border-top: 1px solid #f5f5f5;
    font-size: 14px;
    
    .total-price {
      color: #ff5000;
      font-weight: bold;
    }
  }
}

.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  
  .price-info {
    font-size: 14px;
    
    .total-price {
      color: #ff5000;
      font-weight: bold;
    }
  }
  
  .nut-button {
    border-radius: 20px;
    padding: 0 20px;
  }
}

.picker-container {
  .picker-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #f5f5f5;
    font-size: 16px;
    font-weight: bold;
    
    .close-icon {
      font-size: 20px;
    }
  }
  
  .picker-content {
    max-height: 60vh;
    overflow-y: auto;
    
    .empty-coupons {
      padding: 30px 0;
      text-align: center;
      color: #999;
    }
    
    .free-delivery {
      color: #ff5000;
    }
  }
}
</style>